package org.crl.blogsystem.config;

import cn.dev33.satoken.exception.NotLoginException;
import org.crl.blogsystem.message.ResponseMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MissingServletRequestPartException.class)
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public String handleMissingServletRequestPartException(MissingServletRequestPartException ex) {
        logger.error("Missing request part: {}", ex.getMessage());
        return "Missing request part: " + ex.getMessage();
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public String handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        logger.error("Message not readable: {}", ex.getMessage());
        return "Message not readable: " + ex.getMessage();
    }

    @ExceptionHandler(NotLoginException.class)
    public ResponseMessage<String> handleNotLoginException(NotLoginException ex) {
        return ResponseMessage.fail("未登录或登录已过期");
    }
}
